#include "mytcpsocket.h"
#include <QHostAddress>
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>
#include "mydbcontrol.h"
#include "mydbexec.h"
#include <QJsonArray>
#include <QDateTime>
MyTcpSocket::MyTcpSocket(QObject *parent) : QTcpSocket(parent)
{
connect(this,&MyTcpSocket::readyRead,this,&MyTcpSocket::readyReadSlot);

}

bool MyTcpSocket::setSocketDescriptor(qintptr socketDescriptor, QAbstractSocket::SocketState SocketState, QIODevice::OpenMode openMode)
{
bool ok = QTcpSocket::setSocketDescriptor(socketDescriptor,SocketState,openMode);
if(!ok)return false;


    port = this->peerPort();
    socketDes = socketDescriptor;
    bool ok2;
    quint32 ipv4 = this->peerAddress().toIPv4Address(&ok2);
    if(ok2)
    {
        quint8 ipv4arr[4];
        ipv4arr[0]= ipv4;
        ipv4arr[1]= ipv4 >> 8;
        ipv4arr[2]= ipv4 >> 16;
        ipv4arr[3]= ipv4 >> 24;
        ip = QString("%1.%2.%3.%4").arg(ipv4arr[3]).arg(ipv4arr[2]).arg(ipv4arr[1]).arg(ipv4arr[0]);
    }
    else {

        ip= this->peerAddress().toString();

         }
return true;



}

void MyTcpSocket::readyReadSlot()
{
QByteArray data = this->readAll();
int count=0;
//qDebug() << QString::fromLocal8Bit(data);
for(int i = 0;i < data.length();i++)
{
    if(data.at(i) == '{')
        count++;
    else if(data.at(i) == '}'){
        count--;
        if(count == 0){
            QByteArray temp = data.mid(0,i+1);
            //qDebug() << temp;
            handleFrame(temp);
            data = data.mid(i+1);
            i= -1;
      }
    }
  }
}

void MyTcpSocket::handleFrame(const QByteArray &data)
{
QJsonObject obj=QJsonDocument::fromJson(data).object();
int type = obj.value("type").toInt();
 qDebug()<< type;
if(type == 1001)
{
receiveMessage(obj);
emit sendControlMessage(obj);
}
if(type == 8000)
{
 LoginFeedBack(obj);
}
if(type == 2001 || type == 2002 ||type == 2003)
{
  controlDevice(obj);
}

if(type == 1002)
{
  emit sendControlMessage(obj);
}
if(type == 5001)
{
  userLogin(obj);
}
if(type == 3001)
{
  foundOldMessage(obj);
}
if(type == 6001)
 {
  userGetMyDeviceName(obj);
 }

}

void MyTcpSocket::userLogin(const QJsonObject &obj)
{
    QString userName = obj.value("username").toString();
    QString password = obj.value("password").toString();
    MyDBExec *exec = MyDBControl::getObject()->getExec();
    bool ok = false;
    if(exec != nullptr)
    {
      ok = exec->userLogin(userName,password);

    }

    //QString secret_key;
    if(ok){
        this->userName=userName;
       secretKey.clear();

        srand(time(0));
        for(int i = 0 ;i < 10 ;i++)
        {
            int t= rand()%36;
            char c = t <= 9? t+'0':t-10+'A';
            secretKey.append(c);
        }
       // qDebug() <<  "secret_key==" <<secretKey;
//        int id;
//        ok = exec->userGetId(userName,id);
//        if(ok)
//        {
//            groupList.clear();
//            exec->userGetGroupList(id,groupList);
//            exec->userGetId(userName,userId);
//        }
    }
    QJsonObject re;
    re.insert("type",5001);
    re.insert("user_name",userName);
    re.insert("secret_key",secretKey);
    re.insert("re",ok);
    MyDBControl::getObject()->releaseExec(exec);

    this->write(QJsonDocument(re).toJson());
}

void MyTcpSocket::sendControlMessageSlot(const QJsonObject &obj)
{
    qDebug() << "can to here";
    this->write(QJsonDocument(obj).toJson());
}

void MyTcpSocket::serverDeviceControlToOneSlot(QString index, const QByteArray &data)
{
 if(index != deviceIndex || index.isEmpty() || deviceIndex.isEmpty())
     return;
 this->write(data);
}//绑定到server槽函数
void MyTcpSocket::receiveMessage(const QJsonObject &obj)
{
    QString index=obj.value("index").toString();
    QString identification = obj.value("identification").toString();
    qDebug() << "index="<<index << "ident"<< identification;
    if(identification.isEmpty() || index.isEmpty() || identification != this->deviceIdentification || index != this->deviceIndex)
    {
     QJsonObject re;
     re.insert("type",10000);
     re.insert("error_id",1);
     this->write(QJsonDocument(re).toJson());
     return;
    }

//     int co2 = obj.value("co2").toInt();
//     int uv = obj.value("uv").toInt();
//     double te1=obj.value("te1").toDouble();
//     double hu1=obj.value("hu1").toDouble();
//     int light= obj.value("light").toInt();
//     bool methane=obj.value("methane").toBool();
//     bool fire= obj.value("fire").toBool();
//     bool smoke = obj.value("smoke").toBool();
//     bool inf = obj.value("inf").toBool();
//     int pm2_5 = obj.value("pm2_5").toInt();
//     double te2 = obj.value("te2").toDouble();
//     double hu2 = obj.value("hu2").toDouble();
//     bool correlation = obj.value("correlation").toBool();
//     bool reflex = obj.value("reflex").toBool();\

//    obj.insert("type",1001);
//    obj.insert("index",DataTemp::getObject()->deviceId);
//    obj.insert("password",DataTemp::getObject()->deviceKey);
//    obj.insert("boardid",boardId);
//    obj.insert("tem",tem);
//    obj.insert("hum1",hum1);
//    obj.insert("hum2",hum2);
//    obj.insert("light",light);
//    obj.insert("press",press);
//    obj.insert("water1",water1);
//    obj.insert("water2",water2);

    int boardid = obj.value("boardid").toInt();
    double tem = obj.value("tem").toDouble();
    double hum1 =obj.value("hum1").toDouble();
    double light = obj.value("light").toDouble();
    double press = obj.value("press").toDouble();
    double hum2 =obj.value("hum2").toDouble();
    bool water1 = obj.value("water1").toBool();
    bool water2 = obj.value("water2").toBool();

     MyDBExec *exec = MyDBControl::getObject()->getExec();
     if(exec == nullptr)
     {
         return;
     }
     bool ok;
     ok = exec->receiveMessage(boardid,tem,hum1,light,press,hum2,water1,water2);
     MyDBControl::getObject()->releaseExec(exec);

}

void MyTcpSocket::LoginFeedBack(const QJsonObject &obj)
{
QString index= obj.value("index").toString();
QString password = obj.value("password").toString();
qDebug() << "index" << index;
if(index.isEmpty())
{
 QJsonObject re;
 re.insert("type",8001);
 re.insert("re",false);
 this->write(QJsonDocument(re).toJson());
 qDebug() << "index22" << index;
 return;
}
MyDBExec *exec = MyDBControl::getObject()->getExec();
bool ok = false;
if(exec != nullptr)
{
  ok = exec->deviceLogin(index,password);
MyDBControl::getObject()->releaseExec(exec);
}
QJsonObject re;
//QString secret_key;
if(ok){
    this->deviceIndex=index;
   this->deviceIdentification.clear();

    srand(time(0));
    for(int i = 0 ;i < 10 ;i++)
    {
        int t= rand()%36;
        char c = t <= 9? t+'0':t-10+'A';
        deviceIdentification.append(c);
    }

    re.insert("identification",deviceIdentification);
    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    re.insert("time",time);
   // qDebug() <<  "secret_key==" <<secretKey;

}

re.insert("type",8001);
re.insert("re",ok);

this->write(QJsonDocument(re).toJson());

}

void MyTcpSocket::controlNormalDevice(const QJsonObject &obj)
{
    this->write(QJsonDocument(obj).toJson());
}

void MyTcpSocket::foundOldMessage(const QJsonObject &obj)
{QString secretkey=obj.value("secret_key").toString();
    if(secretkey != secretKey || secretKey.isEmpty())
    {
qDebug() << " error: secretKey error or empty ";
   return;
    }

 int data_type=obj.value("data_type").toInt();
 QString device_id = obj.value("device_id").toString();
 qDebug() << "device_id:send:" << device_id;

if(data_type == 0)
searchTodayMessage(device_id);

}

void MyTcpSocket::searchTodayMessage(QString device_id)
{
    MyDBExec *exec = MyDBControl::getObject()->getExec();
    bool ok = false;
    QJsonArray arr;
    if(exec != nullptr)
    {
    ok=exec->searchTodayMessage(device_id,arr);
    // qDebug() << "arr==" << arr;
    }
    QJsonObject re;
    re.insert("type",3001);
    re.insert("arr",arr);
    this->write(QJsonDocument(re).toJson());
}

void MyTcpSocket::controlDevice(const QJsonObject &obj)
{
QString index = obj.value("index").toString();
QString secretkey=obj.value("secret_key").toString();
if(secretkey !=this->secretKey || this->secretKey.isEmpty())

{
    qDebug() << "error:no login or secretkey error!!";
    return;
}
emit deviceControlToOne( index,QJsonDocument(obj).toJson());

}

void MyTcpSocket::userGetMyDeviceName(const QJsonObject &obj)
{
QString secretkey = obj.value("secret_key").toString();
if(secretkey != this->secretKey)
    return;

MyDBExec *exec = MyDBControl::getObject()->getExec();
bool ok = false;
QJsonArray arr;
if(exec != nullptr)
{
ok=exec->userGetMyDeviceName(userName,arr);
 qDebug() << "arr==" << arr;
}
if(ok)
 {
    qDebug() << "dddd";
  QJsonObject re;
  re.insert("type",6001);
  re.insert("arr",arr);
  this->write(QJsonDocument(re).toJson());
 }

}

